/**
 * FileName:PhoneCodeUtil
 * Author:lwl
 * Date:2018/1/25 18:23
 * Description:
 */
package com.winphone.uvam.utils.phoneCode;

import com.winphone.uvam.common.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PhoneCodeUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(PhoneCodeUtil.class);

    private static Map<String,String> phoneMap = new ConcurrentHashMap<>();

    private PhoneCodeUtil(){}

    private static PhoneCodeUtil instance = null;

    public static PhoneCodeUtil getInstance() {
        if (instance == null) {
            synchronized (PhoneCodeUtil.class){
                if(instance  == null){
                    instance = new PhoneCodeUtil();
                }
            }
        }
        return instance;
    }


    /**
     * 获取map
     * @return
     */
    public Map<String, String> getPhoneCodeMap(){
        if(phoneMap == null){
            return new ConcurrentHashMap<>();
        }
        return phoneMap;
    }

    /**
     * 存储key value
     * @param key
     * @param value
     */
    public void put(String key,String value){
        if(phoneMap != null) {
            phoneMap.put(key, value);
        }
    }

    /**
     * 判断验证码是否失效
     * @param codeValue
     * @return
     */
    public Result codeIsInvalid(String codeValue){
        Result result = new Result();
        result.setSuccess(true);
        if(codeValue == null){
            result.setSuccess(false);
            return result;
        }
        //验证码
        String phoneCode = codeValue.split(",")[0];
        //发送验证码时的时间戳
        long sendCodeTime = Long.valueOf(codeValue.split(",")[1]);
        long now = System.currentTimeMillis();
        //计算验证码是否失效
        long isFailed = (now - sendCodeTime)/(1000 * 60);
        if(isFailed >= 3){
            result.setSuccess(false);
            return result;
        }
        result.setObj(phoneCode);
        return result;
    }

    /**
     * 清空map集合
     */
    public void clearMap(){
        if(phoneMap != null){
            phoneMap.clear();
        }
    }

}
